import type { TreeDataNode, TreeProps } from 'antd';
import { Tree } from 'antd';
import cls from 'classnames';
import React, { useState } from 'react';
import styles from './index.less';

export interface FormTreeProps extends TreeProps {
  value?: React.Key[];
  onChange?: (keys: React.Key[]) => void;
  className?: string;
}

const Index = ({
  treeData = [],
  value = [],
  onChange = () => {},
  className,
  ...props
}: FormTreeProps) => {
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>(value);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(value);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  // 递归 展开勾选的key
  const handleExpandKey = (node: TreeDataNode, arr: React.Key[]) => {
    if (!node) return arr;
    if (!arr.includes(node.key)) {
      arr.push(node.key);
    }
    if (node.children && node.children.length > 0) {
      node.children.forEach((item) => {
        // eslint-disable-next-line no-param-reassign
        arr = handleExpandKey(item, arr);
      });
    }
    return arr;
  };

  const onCheck: TreeProps['onCheck'] = (keys, e) => {
    setCheckedKeys(keys as React.Key[]);
    onChange(keys as React.Key[]);
    if (e.checked) {
      setExpandedKeys(handleExpandKey(e.node, [...expandedKeys]));
    }
    setSelectedKeys(new Array(e.node.key));
  };

  const onExpand: TreeProps['onExpand'] = (expandedKeysValue) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onSelect: TreeProps['onSelect'] = (selectedKeysValue) => {
    setSelectedKeys(selectedKeysValue);
  };

  return (
    <Tree
      checkable
      autoExpandParent={autoExpandParent}
      checkedKeys={checkedKeys}
      selectedKeys={selectedKeys}
      expandedKeys={expandedKeys}
      onExpand={onExpand}
      onCheck={onCheck}
      onSelect={onSelect}
      treeData={treeData}
      showLine={true}
      className={cls(className, styles.tree, styles.treeFormItem)}
      {...props}
    />
  );
};
export default Index;
